package org.shinetour.sms.service.impl;

import cn.hutool.json.JSONObject;
import com.cloopen.rest.sdk.BodyType;

import com.cloopen.rest.sdk.CCPRestSmsSDK;
import org.shinetour.sms.model.ResultModel;
import org.shinetour.sms.model.SmsRecord;
import org.shinetour.sms.service.IRLSmsService;
import org.shinetour.sms.supplier.RLSmsConfig;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * @Description:
 * @Author: ZhenHua Wang
 * @CreateDate: 2020/3/31 17:36
 */
@Service
public class RLSmsServiceImpl implements IRLSmsService {
    /**
     * @Description: 发送单条短信
     * @Author: ZhenHua Wang
     * @CreateDate: 2020/3/31 17:35
     */
    @Override
    public ResultModel<HashMap<String, Object>> sendSms(SmsRecord record) {
        ResultModel<HashMap<String, Object>> res = new ResultModel<>();
        try {
            CCPRestSmsSDK sdk = new CCPRestSmsSDK();
            sdk.init(RLSmsConfig.SERVER_IP, RLSmsConfig.SERVER_PORT);
            sdk.setAccount(RLSmsConfig.ACCOUNT_SID, RLSmsConfig.AUTH_TOKEN);
            sdk.setAppId(RLSmsConfig.APP_ID);
            sdk.setBodyType(BodyType.Type_JSON);
            //JSONObject初始化不排除null值，并且按有序处理，防止因此引起的问题。
            JSONObject transObj = new JSONObject(record.getParams(), false, true);
            String[] datas = transObj.values().toArray(new String[]{});
            HashMap<String, Object> invokeResult = sdk.sendTemplateSMS(record.getMobile(), record.getTemplateCode(), datas);

            if ("000000".equals(invokeResult.get("statusCode"))) {

                res = res.success(invokeResult);
//                //正常返回输出data包体信息（map）
//                HashMap<String, Object> data = (HashMap<String, Object>) result.get("data");
//                Set<String> keySet = data.keySet();
//                for (String key : keySet) {
//                    Object object = data.get(key);
//                    System.out.println(key + " = " + object);
//                }
            } else {
                res = res.error(invokeResult);
//                //异常返回输出错误码和错误信息
//                System.out.println("错误码=" + result.get("statusCode") + " 错误信息= " + result.get("statusMsg"));
            }
        } catch (Exception ex) {
            return res.error("系统错误：供应商短信发送失败，" + ex.getMessage());
        }
        return res;
    }
}
